
//////////////////////// Page Initializing ////////////
//

function decorateUserList() {
	$('#user_list tr:last-child').addClass('last');	
}

//////////////////////// LOADING A PAGE ////////////
//

function loadPage(sourceDiv, actionURL, employeeId) {
		
	$.ajax ({
		type: 	"get",
		url:	  actionURL + "?set_ajax_view",
		data:     "employeeId=" + employeeId, 			
		dataType: "html",
		beforeSend: function() {
			hideStatusMessage();
			$('div#invalid_form').hide();
			$('div#' + sourceDiv).hide();
			toggleModalAjaxLoader();
		},
		complete: 	function() {
			$('div#' + sourceDiv).show();
			toggleModalAjaxLoader();
		},
		success:  function(data) {
			$("#" + sourceDiv).html(data);		
		}
	});	
	$('#employeeListSelector').dialog('close');
}

function filterUserList() {
	$.ajax({
		type: 'GET',
		url: 'Filter?set_ajax_view',
		data: 'deptId=' + $('#deptSelector').val() +
				'&roleGroupId=' + $('#roleSelector').val() +
				'&status=' + $('#statusSelector').val(),
		dataType: 'html',
		success: function(data) {
			$('#userListBody').html(data);
		}			
	});
}

// Select employee to create a new account from

function popUpEmployeeList() {
	$.ajax({
		type: 	'GET',
		url:	'../HumanResources/ListForUserPage?set_ajax_view',
		dataType: 'html',
		success: function(data) {
			var buttons = {};
			buttons[_('Close')] = function() {
				$(this).dialog('close');							
			};
			
			generalDialog('employeeListSelector', _('Select employee to create account'), data, 'error', {
				autoOpen: true,		
				bgiframe: true,
				height: 450,
				width:	850,
				resizable: false,
				modal: true,
				buttons: buttons,
				dialogClass: 'custom-dialog'
			}, _('Close'));
		}
	});
}


function loadEmployeeList(deptId, typeId, mapped) {
	hideStatusMessage();
	$.ajax ({
		type:	'GET',
		url:	'../HumanResources/GetEmployeeListForUserPage?set_ajax_view',
		data:	'deptId=' + deptId + '&typeId=' + typeId + '&mapped=' + mapped,	
		success: function(data) {
			$('#employeeListResult').html(data);
			$('#employeeList tr:last').addClass('last');
		}
	});
}

function selectEmployee(sourceDiv, actionURL, employeeId) {
	loadPage(sourceDiv, actionURL, employeeId);
	$('#employeeListSelector').dialog('close');
}
//////////////////////// ACTION UPDATE USER ////////////
//
function editUser() {
	if (!checkMonth($('#dob_mm'),false,'','error_message')) {
		$('div#invalid_form').show();
		return;
	} 
	
	if (!checkDay($('#dob_dd'),false,'','error_message')) {
		$('div#invalid_form').show();	
		return;
	}	
	var res 	= 	checkDate($('#dob_yyyy'),$('#dob_mm'),$('#dob_dd'), false, '', 'error_message', true);
	if(!res){
		$('div#invalid_form').show();
		return ;
	}
	
	
	var date = $.trim($('#dob_dd').val());
	var month = $.trim($('#dob_mm').val());
	var year = $.trim($('#dob_yyyy').val());
	if (date.length == 0) {
		date = 1;
	} 
	if (month.length == 0) {
		month = 1;
	}		
	if (!validateForm()) {
		return;
	}	   
    
	$.ajax({
		type:		"POST",
		url:		"EditUserAjax?set_ajax_view",		
		data:		$('#employeeForm').serialize() +
			'&' + $('#userAccountForm').serialize(),				
		beforeSend: function() {
			hideStatusMessage();			
			$('div#barLoading').show("fast");
		},
		complete: 	function() {						
			$('div#barLoading').hide("fast");
			$('div#invalid_form').hide();
		},
		success:	function(data) {	
			dataValue = parseInt(data);
			// Unexpected error
			if (dataValue == -1) {
				showCustomDialog(_('Error'),
						_('Unexpected error, please try again'), 'error');
			}
			// duplicated username
			else if (dataValue == -2) {
				showCustomDialog(_('Error'),
						_('Duplicated username, please try again'), 'error');
			}
			// success
			else {							
				showCustomDialog(_('Update user'), 
						_('Update successfully'), 'ok');
				$.ajax ({
					type: 	"get",
					url:	  "Edit?set_ajax_view",
					data:     "employeeId=" + dataValue, 			
					dataType: "html",					
					success:  function(data) {
						$("#userManagementContent").html(data);			
					}
				});	
			}
		} 																
	});		
}

function showCustomDialog(title, message, iconType) {
	var buttons = {};
	buttons[_('Close')] = function() {
		$(this).dialog('close');
	};
	
	generalDialog(null, title, message, iconType, {
		autoOpen: true,			
		bgiframe: true,
		resizable: false,
		modal: true,
		buttons: buttons,
		dialogClass: 'custom-dialog'
	}, _('Close'));
}

function showErrorMessage(title, message) {
	$('#status_message').find('span.failure').text(title);
	$('#status_message').find('p').text(message);
	$('#status_message').find('span.success').hide();
	$('#status_message').find('span.failure').show();	
	$('#status_message').show('fast'); 
}
function showStatusMessage(title, message) {
	$('#status_message').find('span.success').text(title);
	$('#status_message').find('p').text(message);
	$('#status_message').find('span.failure').hide();
	$('#status_message').find('span.success').show();	
	$('#status_message').show('fast'); 
}

function hideStatusMessage(){
	$('#status_message').hide('fast');
}

function validateForm() {
	
	var message = "";
	if(!isNotEmpty($('#name'),'','error_message')) {
		return displayError(_("Empty name"));
	}
	
	if( $("input:radio[name='employee[gender]']:checked").length == 0) {
		return displayError(_("Not yet select gender"));
	}
	/*
	if( $("#room").val() == "") {
		return displayError("Chưa chọn phòng làm việc");
	}
	*/
	if( !isNotEmpty($('#username'),'','error_message')) {
		return displayError(_("Empty account"));
	} else if (!$.trim($('#username').val()).match(/^[a-zA-Z][a-zA-Z0-9_-]*$/)) {
		return displayError(_('Invalid account'));		
	}
	if( !isNotEmpty($('#password'),'','error_message')) {
		return displayError(_('Empty password'));
	}
	$('#password_match').css("border-color", "#AAA");
	if ( ($('#password').attr('disabled') != 'disabled') &&
			($('#password').val() != $('#password_match').val())) {
		$('#password_match').css("border-color", "red");
		return displayError(_("Password doesn't match"));
	} 
	$('#groups').css("border-color", "#AAA");
	if ( $('#groups option:selected').length == 0) {
		$('#groups').css("border-color", "red");
		return displayError(_("Not yet select role in the system"));
	}
	
	return true;				
}

function displayError(message) {
	$('div#invalid_form > span:first').text(message);
	$('div#invalid_form').show();
	return false;
}

///// Move some items between two listboxes for mapping rooms of employee.
function moveItem(option) {
    if (option == 'add') {
        //Append the item in Target Listbox
        $("#roomList").copyOptions("#mappedRoomList");
        
    } else if (option == 'remove') {
        //Remove the item from Source Listbox
        $("#mappedRoomList").removeOption(/./, true);
    }
    return false;
}

///// Insert the default room into the mapped rooms of employee.
function mapDefaultRoom() {
    if ($("#room").val() != "") {
        $("#mappedRoomList").addOption($("#room").val(), $("#room option:selected").text());
    }
}
